package cn.le;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class MqConfig {

    @Bean
    public Queue queue(){
        return new Queue("rtu-inst_queue");
    }

	@Bean
	public FanoutExchange defaultExchange() {
		return new FanoutExchange("rtu-instruction-exchange");
	}

	@Bean
	public Binding binding(Queue queue, FanoutExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange);
	}


	/**
	 * 给 test_queue 队列配置私信队列
	 * 私信队列也是正常的交换机->队列
	 * 消息进入私信队列:
	 * 1.消息被拒绝(（basic.reject/ basic.nack）并且不再重新投递 requeue=false),channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
	 * 2.消息超时 (rabbitmq  Time-To-Live -> messageProperties.setExpiration())
	 * 3.队列超载
	 *
	 * 消息编程死信后,被重新投递(publish)到另一个exchange,改exchange就是DLX,然后改exchange根据绑定规则,转发到对应的队列上(换个地方重新消费)
	 */
	@Bean(name = "test_dxl_exchange")
	public Exchange dxlExchange() {
		return new DirectExchange("test_dxl_exchange");
	}

	@Bean("test_dxl_queue")
	public Queue dxlQueue() {
		return new Queue("test_dxl_queue");
	}

	@Bean(name = "dxl_binding")
	public Binding dxlBinding(@Qualifier("test_dxl_queue") Queue queue, @Qualifier("test_dxl_exchange") DirectExchange exchange) {
		return BindingBuilder.bind(queue).to(exchange).with("key_r");
	}


	@Bean(name = "test_queue")
	public Queue testQueue(){
		Map<String, Object> args = new HashMap<>(2);
//       x-dead-letter-exchange 申明私信队列交换机
		args.put("x-dead-letter-exchange", "test_dxl_exchange");
//       x-dead-letter-routing-key   声明 死信路由键
		args.put("x-dead-letter-routing-key", "key_r");
		return QueueBuilder.durable("test_queue").withArguments(args).build();
	}

	@Bean(name = "test_exchange")
	public FanoutExchange testExchange() {
		return new FanoutExchange("test_exchange");
	}
	@Bean(name = "test_binding")
	public Binding testBinding(@Qualifier("test_queue") Queue queue, @Qualifier("test_exchange") FanoutExchange exchange) {
		return BindingBuilder.bind(queue).to(exchange);
	}
}
